// 网络请求封装

const HttpTool = {};

/**
 * GET请求
 */
HttpTool.get = function(url, params, headers) {
  if (params) {
    let paramsArray = [];

    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&')
    } else {
      url += '&' + paramsArray.join('&')
    }
  }

  return new Promise(function(resolve, reject) {
    fetch(url, {
      method: 'GET',
      headers: headers,
    })
    .then(response => {
      resolve(response.json());
    })
    .catch(err => {
      reject(err);
    })
  })
};

/**
 * POST请求  FormData 表单数据
 */
HttpTool.post = function(url, params, headers) {
  const _headers = {
    "Content-Type": "application/json",
  };

  if (headers) {
    Object.keys(headers).forEach(key => {
      _headers[key] = headers[key]
    });
    console.log(_headers);
  }

  return new Promise(function(resolve, reject) {
    fetch(url, {
      method: 'POST',
      headers: _headers,
      body: JSON.stringify(params),
    })
    .then(response => {
      // console.warn(response.headers.get('token'));
      resolve && resolve(response.json());
    })
    .catch(err => {
      reject && reject(err);
    })
  })
};

export default HttpTool;